﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EventReminder.Common;
using System.IO;

namespace EventReminder.Server
{
    public class EventManager
    {
        List<EventData> alleventdata;

        public EventManager()
        {
            alleventdata = new List<EventData>();
        }

        private string GetSession(string name)
        {
            string datavalue = "";
            Random rand = new Random();

            datavalue = name + rand.Next().ToString();

            return datavalue;
        }

        public void AddEvent(EventData e)
        {
            alleventdata.Add(e);
        }

        public List<EventData> GetMessageQueue(int interval)
        {
            List<EventData> returnlist = new List<EventData>();
            DateTime today = DateTime.Now;
            TimeSpan intervalcheck;
            int days;

            foreach (EventData e in alleventdata)
            {
                intervalcheck = e.Date - today;
                days = intervalcheck.Days;
                if (days < interval)
                {
                    returnlist.Add(e);
                }
            }


            return returnlist;
        }

        public void GetMessageSend(int interval)
        {
            //List<Event> returnlist = new List<Event>();
            bool send = false;

            foreach (EventData e in alleventdata)
            {
                send = CheckForMessageSend(interval, e);
                if (send)
                    e.FollowUp = true; //returnlist.Add(e);
            }


            //return returnlist;
        }

        public bool CheckForMessageSend(int interval, EventData e)
        {
            bool send = false;
            
            DateTime today = DateTime.Now;
            TimeSpan intervalcheck;
            int days;
            int minutes;

            intervalcheck = e.Date - today;
            days = intervalcheck.Days;
            if (days < interval)
            {
                minutes = (intervalcheck.Hours * 60) + intervalcheck.Minutes;
                if (minutes < 5)
                {
                    send = true;
                }
            }

            return send;
        }

        public void MarkMessagesToSend(int interval)
        {
            bool send = false;

            foreach (EventData e in alleventdata)
            {
                send = CheckForMessageSend(interval, e);
                if (send)
                    e.Send = true;
            }
        }

        public void MarkMessagesToArchive()
        {
            bool send = false;

            foreach (EventData e in alleventdata)
            {
                send = e.Send;
                if (send)
                    e.Archive = true;
            }
        }

        public List<EventData> GetUserMessage(int userid)
        {
            List<EventData> returnlist = new List<EventData>();

            foreach (EventData e in alleventdata)
            {
                //Update t correct value
                if (e.MessageOwner == userid)
                {
                    returnlist.Add(e);
                }
            }

            return returnlist;
        }

        public List<string> GetMessagesToSend
        {
            get
            {
                List<string> returndata = new List<string>();

                //1|4/20/2012 05:20:00 PM|Test event one|Setup test on how this data needs to be setup.|test@test.net|?|false|4/20/2012 05:20:00 PM|4/20/2012 05:20:00 PM
                foreach (EventData e in alleventdata)
                {
                    if (e.Send)
                    {
                        string dataline = e.Date + "|" + e.Title + "|" + e.Description + "|" + e.Emails;
                        returndata.Add(dataline);
                        //Update EventData object
                        e.Archive = true;
                    }
                }
                return returndata;
            }
        }

        private string GetEmailString(EventData e)
        {
            string[] emaildata = (string[])e.Emails;
            string estring = "";
            int count = emaildata.Count();
            foreach (string s in emaildata)
            {
                estring += s;
                if (count > 1)
                    estring += ";";
            }

            return estring;
        }

        public string WriteEvent(EventData e)
        {
            
                string returndata;
                //1|4/20/2012 05:20:00 PM|Test event one|Setup test on how this data needs to be setup.|test@test.net|1|?|false|4/20/2012 05:20:00 PM|4/20/2012 05:20:00 PM
                returndata = e.ID + "|";
                returndata += e.Date + "|";
                returndata += e.Title + "|";
                returndata += e.Description + "|";
                returndata += GetEmailString(e) + "|";
                returndata += e.Reminder + "|";
                returndata += (int) e.Type + "|";
                returndata += e.FollowUp + "|";
                returndata += e.LastReminderSent + "|";
                returndata += e.NextReminderDue + "|";
                returndata += e.MessageOwner;

                return returndata;
         
        }

        public List<string> DisplayAllEvents
        {
            get
            {
                List<string> returndata = new List<string>();

                //1|4/20/2012 05:20:00 PM|Test event one|Setup test on how this data needs to be setup.|test@test.net|?|false|4/20/2012 05:20:00 PM|4/20/2012 05:20:00 PM
                foreach (EventData e in alleventdata)
                {
                    string dataline = e.Date + "\t" + e.Title + "\t" + GetEmailString(e) + "\t" + e.Reminder + "\t" + e.FollowUp + "\t";
                    //string dataline = e.EventTime + "\t" + e.EventTitle + "\t" + e.EmailList + "\t" + e.Reminder + "\t" + e.EventFollowup + "\t";
                    returndata.Add(dataline);  
                }
                return returndata;
            }
        }

        public bool SendMessages()
        {
            bool result = false;

            foreach (EventData e in alleventdata)
            {

            }

            return result;
        }

        public void AddNewEvent(EventData e)
        {
            try
            {
                using (StreamWriter sw = new StreamWriter(
                    new FileStream(
                        @"..\..\..\Data\eventrecords.txt", FileMode.Append, FileAccess.Write)))
                {
                    sw.WriteLine(this.WriteEvent(e));
                }
            }
            catch
            {

            }
        }

        public void SaveAllEvents()
        {
            try
            {
                using (StreamWriter sw = new StreamWriter(
                    new FileStream(
                        @"..\..\..\Data\eventrecords.txt", FileMode.Create, FileAccess.Write)))
                {
                    foreach (EventData e in alleventdata)
                    {
                        sw.WriteLine(this.WriteEvent(e));
                    }
                }
            }
            catch
            {

            }
        }

        private int FindEventIndex(EventData ed)
        {
            int index = 0;

            foreach (EventData e in alleventdata)
            {
                if (e.ID == ed.ID)
                {
                    break;
                }
                else
                    index++;
            }
            return index;
        }

        public void DeleteEvent(EventData deleteevent)
        {
            RefreshEventList();
            int index = FindEventIndex(deleteevent);
            alleventdata.RemoveAt(index);

            SaveAllEvents();
        }

        public void ModifyEvent(EventData oldversion, EventData newversion)
        {
            RefreshEventList();
            int index = FindEventIndex(oldversion);
            alleventdata[index] = newversion;

            SaveAllEvents();
        }

        public void RefreshEventList()
        {
            try
            {
                alleventdata.Clear();
                using (StreamReader textIn = new StreamReader(
                    new FileStream(
                         @"..\..\..\data\eventrecords.txt", FileMode.OpenOrCreate, FileAccess.Read)))
                {
                    while (textIn.Peek() != -1)
                    {
                        string row = textIn.ReadLine();
                        EventData e = CreateEvent(row);
                        alleventdata.Add(e);
                    }
                }
            }

            catch
            {

            }
        }

        public EventData CreateEvent(string data)
        {
            string[] dataline;
            dataline = data.Split('|');
            EventData e = new EventData();

            e.ID = Convert.ToInt32(dataline[0]);
            e.Date = Convert.ToDateTime(dataline[1]);
            e.Title = dataline[2];
            e.Description = dataline[3];
            string[] emaillist = dataline[4].Split(';');
            e.Emails = emaillist;
            e.Reminder = dataline[5];
            e.Type = (EventTypes) Convert.ToInt32(dataline[6]);
            e.FollowUp = Convert.ToBoolean(dataline[7]);
            e.LastReminderSent = Convert.ToDateTime(dataline[8]);
            e.NextReminderDue = Convert.ToDateTime(dataline[9]);
            e.MessageOwner = Convert.ToInt32(dataline[10]);
            return e;
        }
    }
}
